<template>
    <div class="container-box">
        <topMenu ref="rightMenuRef"/>
        <div class="flex justify-between wrapper-box">

            <div class="flex-sub left-box padding-top padding-lr-xl text-sm">
                <div v-loading="loading" class="img-list text-14 flex align-center justify-center flex-direction">
                    <div v-if="imageUrl.length>0" class="actionDiv flex justify-center">
                        <div class="items flex align-center" @click="downImage(imageUrl[0])">
                            <el-icon>
                                <Download/>
                            </el-icon>
                            下载
                        </div>
                        <div class="items flex align-center" @click="resetAction">
                            <el-icon>
                                <Refresh/>
                            </el-icon>
                            重置
                        </div>
                        <div class="items flex align-center" @click="delAction">
                            <el-icon>
                                <Close/>
                            </el-icon>
                            删除
                        </div>
                    </div>
                    <!--<div v-if="imageUrl.length>0" class="image-arr">-->
                    <!--    <img v-for="(item,index) in imageUrl" :src="item">-->
                    <!--</div>-->
                    <div v-if="imageUrl.length>0" class="image-arr flex justify-center align-center flex-direction">
                        <div class="image-first flex" style="width: 5.333rem;height: 5.333rem">
                            <img :src="imageUrl[0]" style="width: 100%;object-fit: contain;">
                        </div>
                        <div class="image-more flex justify-center margin-top-sm">
                            <template v-for="(item,index) in imageUrl">
                                <img v-if="index>0" :src="item" style="width:1.6rem;height:1.6rem;object-fit: contain;">
                            </template>
                        </div>
                    </div>

                    <el-upload v-else v-model:file-list="fileList" :action="uploadAction"
                               :before-upload="beforeImageUpload" :headers="uploadHeaders" :limit="1"
                               :on-error="handleImageError" :on-success="handleImageSuccess" class="upload-demo"
                               multiple>
                        <div class="flex flex-direction justify-center align-center">
                            <div class="upload-tip-box flex align-center justify-center margin-bottom-xs flex-direction">
                                <el-icon color="#fff" size="50">
                                    <Picture/>
                                </el-icon>
                                <span class="text-white">没有参考图</span>
                            </div>
                            <el-button type="primary">
                                <el-icon>
                                    <UploadFilled/>
                                </el-icon>
                                上传
                            </el-button>
                        </div>
                    </el-upload>
                    <div class="imgBtnList flex align-center flex-wrap justify-between">
                        <el-button v-for="(items,indexs) in imgBtnList"
                                   class="imgBtnList-items flex align-center justify-center margin-top-sm"
                                   type="primary" @click="imgBtnClick(items)">
                            {{ items.label }}
                        </el-button>
                    </div>
                </div>
                <div class="flex align-center margin-top-sm">
                    <el-input v-model="textarea" :autosize="{ minRows:1, maxRows: 4 }"
                              class="input-box text-xs margin-right-xs" placeholder="请告诉我你的想法" type="textarea"/>
                    <el-button type="primary" @click="handleCreated">图片生成</el-button>
                </div>
            </div>
            <div v-if="!showNav" class="right-menu padding-sm">
                <rightMenu ref="rightMenuRef"/>
            </div>
            <div v-if="showNav" class="nav-menu flex align-center justify-center" @click="drawer = true">
                <el-icon>
                    <Grid/>
                </el-icon>
            </div>
            <el-drawer v-model="drawer" direction="rtl" size="100%">
                <template #header>
                    <div class="text-df text-white">请通过以下面板配置您的要求</div>
                </template>
                <template #default>
                    <rightMenu ref="rightMenuRef"/>
                </template>
                <template #footer>
                    <div style="flex: auto">
                        <el-button @click="cancelClick">cancel</el-button>
                        <el-button type="primary" @click="confirmClick">confirm</el-button>
                    </div>
                </template>
            </el-drawer>
        </div>
    </div>
</template>

<script lang="ts" setup="">
    import _ from 'lodash';
    import socket from '../../http/websocket'
    import rightMenu from '../../components/right-menu.vue';
    import topMenu from '../../components/topMenu.vue';
    import {onMounted, ref, watch} from "vue";
    import {ElMessage} from 'element-plus'
    import type {UploadProps, UploadUserFile} from 'element-plus'
    import {drawSDAdd, drawMJAdd, drawMjModify} from "../../http/draw";
    import commonStore from '../../store/common'
    import useUserStore from '../../store/user'
    import {getToken} from "../../plugins/cookie";

    const store_common: any = commonStore()
    const store_user: any = useUserStore()

    const loading = ref(false)

    // console.log("import.meta.env.VITE_LOCATION_ORIGIN", import.meta.env.VITE_LOCATION_ORIGIN)
    const imageUrl = ref([]) //上传的图片
    const uploadAction = ref(`${import.meta.env.VITE_LOCATION_ORIGIN}/api/upload`) //上传图片传递的action
    const uploadHeaders = ref({
        'Authorization': `Bearer ${getToken()}`
    })
    const button_message_id = ref('') // MJ模型返回的按钮集合选项ID
    let imgBtnList = ref([])
    const fileId = ref('') //上传文件成功后的文件ID
    const drawer = ref(false) //手机版弹窗
    const textarea = ref('')  //输入的提示语
    const showNav = ref(false); //
    const screenWidth = ref(document.body.clientWidth)
    const rightMenuRef = ref('');
    const rightMenuRefObj = ref({})

    showNav.value = screenWidth.value < 1024;
    onMounted(() => {
        window.onresize = () => {
            return (() => {
                screenWidth.value = document.body.clientWidth
            })()
        }
        socket.init()
    })
    watch(() => [screenWidth.value, store_common.socketMsg], (val: any) => {
        console.log("val", val)
        showNav.value = val[0] < 1024;
        console.log('showNav', showNav)
        screenWidth.value = val[0]

        if (screenWidth.value < 1024) {
            store_user.setPlatform('moblie')
        } else {
            store_user.setPlatform('PC')
        }

        if (val[1]) {
            let data = val[1]
            console.log("data", data, data.data.images);
            if (data.data.images) {
                console.log("images___11", data, data.data.images);
                imageUrl.value = data.data.images
                loading.value = false;
            }
            if (data.data.button) {
                button_message_id.value = data.data.button_message_id
                imgBtnList.value = data.data.button
            } else {
                imgBtnList.value = []
            }
        }

    }, {deep: true})

    let fileList = ref<UploadUserFile[]>([])
    //图片上传成功
    const handleImageSuccess: UploadProps['onSuccess'] = (
        response,
        uploadFile
    ) => {
        console.log("图片上传成功回调", response, uploadFile);
        if (response.code === 0) {
            imageUrl.value = [response.data.url]
            console.log("imageUrl", imageUrl)
            fileId.value = response.data.file_id
        }
    }

    //图片上传失败
    const handleImageError: UploadProps['onError'] = (
        response,
        uploadFile
    ) => {
        console.log("图片上传失败回调", response, uploadFile);
        // imageUrl.value = URL.createObjectURL(uploadFile.raw!)
    }

    //图片上传之前校验
    const beforeImageUpload: UploadProps['beforeUpload'] = (rawFile) => {
        // 上传图片前判断
        const isImage = rawFile.type == 'image/png' || rawFile.type == 'image/jpg' || rawFile.type == 'image/jpeg' || rawFile.type == 'image/bmp' || rawFile.type == 'image/gif' || rawFile.type == 'image/webp';
        const isLt50M = rawFile.size < 1024 * 1024 * 50;
        if (!isImage) {
            ElMessage.error('上传只能是png,jpg,jpeg,bmp,gif,webp格式!');
        }
        if (!isLt50M) {
            ElMessage.error('上传图片大小不能超过 1MB!');
        }
        return isImage && isLt50M;
    }

    //关闭抽屉
    const cancelClick = () => {
        drawer.value = false;
    }

    const confirmClick = () => {
        console.log("rightMenuRef", rightMenuRef.value)
        rightMenuRefObj.value = Object.assign({}, rightMenuRef.value)
        cancelClick()
    }

    //MJ模型图形优化操作
    const imgBtnClick = (item) => {
        console.log("item", item);
        let paramsData = {
            button_message_id: button_message_id.value,
            button_type: item.custom_id
        }
        console.log("paramsData", paramsData)
        loading.value = true;
        drawMjModify(paramsData).then(res => {
            const {data} = res;
            console.log("drawMjModify", data)
        })
    }

    //图片生成
    const handleCreated = () => {
        if (!textarea.value) {
            ElMessage.error(`请先输入你的想法哦~`)
            return
        }

        let paramsData = {
            prompt: `${textarea.value},`
        }

        let settingSD, settingMJ, platform, promptCategoryList;

        if (showNav.value) {
            platform = rightMenuRefObj.value.platform
            settingSD = rightMenuRefObj.value.settingSD
            settingMJ = rightMenuRefObj.value.settingMJ
            promptCategoryList = rightMenuRefObj.value.promptCategoryList
        } else {
            platform = rightMenuRef.value.platform
            settingSD = rightMenuRef.value.settingSD
            settingMJ = rightMenuRef.value.settingMJ
            promptCategoryList = rightMenuRef.value.promptCategoryList
        }

        console.log("settingSD", settingSD, settingMJ, platform)

        if (platform === 'sd' && settingSD.length > 0) {
            for (let item of settingSD) {
                if (item.type === 1) {
                    if (item.is_required === 1) {
                        if (item.isSelected) {
                            paramsData[`${item.code}[id]`] = item.isSelected
                        } else {
                            ElMessage.error(`请先选择${item.name}`)
                            return;
                        }
                    }
                } else if (item.type === 2) {
                    if (item.is_required === 1) {
                        let index = _.findIndex(item.setting, {'isSelected': true});
                        console.log("index", index)
                        if (index > -1) {
                            paramsData[`${item.code}[id]`] = item.setting[index].id
                        } else {
                            ElMessage.error(`请先选择${item.name}`)
                            return;
                        }
                    }
                } else {
                    paramsData[`${item.code}[id]`] = item.setting[0].id
                    paramsData[`${item.code}[value]`] = item.values
                }
            }

        }
        if (platform === 'mj' && settingMJ.length > 0) {
            for (let item of settingMJ) {
                let index = _.findIndex(item.setting, {'isSelected': true});
                console.log("index", index)
                if (index > -1) {
                    paramsData[`${item.code}`] = item.setting[index].id
                } else {
                    ElMessage.error(`请先选择${item.name}`)
                    return;
                }
            }
        }

        let prompt = ''
        let promptArr = []
        promptCategoryList.map(item => {
            let prompt = item.prompt
            prompt.map(items => {
                if (items.isSelected) {
                    promptArr.push(items.name)
                }
            })
        })
        prompt = promptArr.join(',')
        paramsData.prompt = paramsData.prompt + prompt

        if (fileId) {
            paramsData.image_id = fileId.value
        }

        console.log("handleCreated", paramsData)
        if (platform === 'sd') {
            drawSDAdd(paramsData).then(res => {
                loading.value = true;
                console.log("res", res)
                const {data} = res;
                console.log("drawSDAdd", data)
            })
        } else if (platform === 'mj') {
            drawMJAdd(paramsData).then(res => {
                loading.value = true;
                console.log("res", res)
                const {data} = res;
                console.log("drawMJAdd", data)
            })
        }
    }

    //图片下载
    const downImage = async (href, name) => {
        console.log("download", href, name)
        // 获取图片对象和画布对象
        const imgUrl = href
        const response = await fetch(imgUrl)
        const blob = await response.blob()
        // 创建下载链接
        const url = window.URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.href = url
        link.download = name ? name : '图片下载'
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        // 释放 Blob URL
        window.URL.revokeObjectURL(url)
    }

    //重置操作
    const resetAction = () => {
        if (fileId) {
            fileId.value = ''
            fileList.value = [];
        }
        imageUrl.value = [];
        textarea.value = null;
    }

    const delAction = () => {
        if (fileId) {
            fileId.value = ''
            fileList.value = [];
        }
        imageUrl.value = [];
    }
</script>

<style lang="scss" scoped>
  @import "@/assets/css/variables.scss";

  .container-box {
    background-color: $Secondary3;
    color: $Secondary4;
  }

  .upload-tip-box {
    width: 4rem;
    height: 2.8rem;
    border-radius: 0.133rem;
    background-color: rgba(0, 0, 0, .2);
  }

  .left-box {
    overflow: hidden;
    overflow-y: auto;

    .img-list {
      position: relative;
      background-color: $Secondary4;
      color: $gray2;
      border-radius: 0.267rem;
      height: calc(80vh);
      padding: 0.4rem;
      background: linear-gradient(135deg, rgba(185, 187, 186, 0.5), rgba(185, 187, 186, 0.5) 25%, transparent 0px, transparent 50%, rgba(185, 187, 186, 0.5) 0px, rgba(185, 187, 186, 0.5) 75%, transparent 0px, transparent) 0% 0% / 4px 4px;

      .actionDiv {
        position: absolute;
        width: 100%;
        top: 20px;

        .items {
          cursor: pointer;
          border: $Secondary2 1px solid;
          color: $Secondary2;
          border-radius: 4px;
          padding: 5px 16px;
          background-color: $Secondary3;
          margin: 0 10px;
        }
      }
    }

    .imgBtnList {
      width: 4rem;

      .imgBtnList-items {
        width: 0.733rem;
        height: 0.4rem;
        text-align: center;

        &:nth-child(5) {
          margin-left: 0;
        }
      }
    }

    .input-box {
      ::v-deep .el-textarea__inner {
        background-color: $Secondary4;
        color: #757575;
        border-radius: 0.133rem;
      }
    }
  }

  .right-menu {
    width: 5.333rem;
    background-color: $theme;
    height: 100%;
    overflow-y: auto;
  }

  ::v-deep .el-drawer {
    background-color: $theme;
  }

  .nav-menu {
    position: fixed;
    right: 0.267rem;
    bottom: 20vh;
    background-color: #fff;
    border-radius: 50%;
    width: 1.333rem;
    height: 1.333rem;
  }
</style>
